package com.maxlen.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maxlen.common.constant.WareConstant;
import com.maxlen.common.utils.PageUtils;
import com.maxlen.common.utils.R;
import com.maxlen.common.vo.PageParamsVO;
import com.maxlen.ware.dao.PurchaseDao;
import com.maxlen.ware.dao.WareSkuDao;
import com.maxlen.ware.entity.PurchaseDetailEntity;
import com.maxlen.ware.entity.PurchaseEntity;
import com.maxlen.ware.entity.WareSkuEntity;
import com.maxlen.ware.entity.vo.PurchaseDoneVO;
import com.maxlen.ware.entity.vo.PurchaseItemVO;
import com.maxlen.ware.entity.vo.PurchaseMergeVO;
import com.maxlen.ware.feign.PurchaseFeignService;
import com.maxlen.ware.entity.to.SkuInfoTO;
import com.maxlen.ware.service.PurchaseDetailService;
import com.maxlen.ware.service.PurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private PurchaseFeignService purchaseFeignService;

    @Override
    public PageUtils queryPage(PageParamsVO params) {
        LambdaQueryWrapper<PurchaseEntity> wrapper = new LambdaQueryWrapper<>();

        String key = params.getKey();
        if(StringUtils.hasText(key)){
            wrapper.like(PurchaseEntity::getAssigneeName, key);
        }

        IPage<PurchaseEntity> page = this.page(
                new Page<>(params.getPage(), params.getLimit()),
                wrapper
        );

        return new PageUtils(page);
    }


    @Override
    public PageUtils getUnReceive(PageParamsVO params) {
        LambdaQueryWrapper<PurchaseEntity> wrapper = new LambdaQueryWrapper<>();

        IPage<PurchaseEntity> page = this.page(
                new Page<>(params.getPage(), params.getLimit()),
                wrapper.eq(PurchaseEntity::getStatus, 0).or().eq(PurchaseEntity::getStatus, 1)
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void mergePurchase(PurchaseMergeVO purchaseMergeVO) {
        Long purchaseId = purchaseMergeVO.getPurchaseId();
        if(purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseEnum.CREATE.getCode());
            baseMapper.insert(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //TODO 确认采购单状态是 0，1 才可以合并

        List<Long> items = purchaseMergeVO.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntityList = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);
    }

    @Override
    @Transactional
    public void received(List<Long> ids) {
        // 判断采购单是否为分配状态
        List<PurchaseEntity> purchaseEntityList = baseMapper.selectBatchIds(ids);

        List<PurchaseEntity> entityList = purchaseEntityList.stream().filter(purchase -> {
            return purchase.getStatus() == WareConstant.PurchaseEnum.ASSIGNED.getCode();
        }).map(purchase -> {
            purchase.setStatus(WareConstant.PurchaseEnum.RECEIVE.getCode());
            return purchase;
        }).collect(Collectors.toList());

        // 更新采购单的状态为已领取状态
        this.updateBatchById(entityList);

        // 更新采购需求的状态为正在采购
        purchaseDetailService.updateStatusByPurchaseIds(ids);
    }

    @Override
    @Transactional
    public void finish(PurchaseDoneVO purchaseDoneVO) {

        List<PurchaseItemVO> purchaseItemVOList = purchaseDoneVO.getItems();

        boolean purchaseStatus = true;

        List<PurchaseDetailEntity> entityList = new ArrayList<>();
        List<Long> purchaseDetailIds = new ArrayList<>();
        for (PurchaseItemVO purchaseItemVO : purchaseItemVOList) {

            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(purchaseItemVO.getItemId());
            purchaseDetailEntity.setStatus(purchaseItemVO.getStatus());
            entityList.add(purchaseDetailEntity);

            if(purchaseItemVO.getStatus() == WareConstant.PurchaseDetailEnum.HASE_ERROR.getCode()){
                purchaseStatus = false;
            }else{
                purchaseDetailIds.add(purchaseItemVO.getItemId());
            }
        }
        // 改变采购需求的状态
        purchaseDetailService.updateBatchById(entityList);

        // 改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVO.getId());
        if(purchaseStatus){
            purchaseEntity.setStatus(WareConstant.PurchaseEnum.FINISH.getCode());
        }else{
            purchaseEntity.setStatus(WareConstant.PurchaseEnum.HASE_ERROR.getCode());
        }
        baseMapper.updateById(purchaseEntity);

        // 将成功的采购进行入库
        if(!purchaseDetailIds.isEmpty()){
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailService.getListByIds(purchaseDetailIds);
            for (PurchaseDetailEntity purchaseDetailEntity : purchaseDetailEntityList) {
                Long skuId = purchaseDetailEntity.getSkuId();
                Long wareId = purchaseDetailEntity.getWareId();
                Long aLong = wareSkuDao.selectCount(new LambdaQueryWrapper<WareSkuEntity>()
                        .eq(WareSkuEntity::getSkuId, skuId)
                        .eq(WareSkuEntity::getWareId, wareId));
                if(aLong > 0){
                    wareSkuDao.updateStock(skuId, wareId, purchaseDetailEntity.getSkuNum());
                }else{
                    WareSkuEntity wareSkuEntity = new WareSkuEntity();
                    wareSkuEntity.setSkuId(skuId);
                    wareSkuEntity.setWareId(wareId);
                    wareSkuEntity.setStock(purchaseDetailEntity.getSkuNum());
                    //TODO 远程查询 sku 的名字，如果失败，整个失误无需回滚（自己 catch 异常）
                    //TODO 还可以用什么办法让异常出现以后不会滚
                    try{
                        R info = purchaseFeignService.info(skuId);
                        if(info.getCode() == 0){
                            SkuInfoTO skuInfo = (SkuInfoTO) info.get("skuInfo");
                            wareSkuEntity.setSkuName(skuInfo.getSkuName());
                        }
                    }catch (Exception e){}

                    wareSkuDao.insert(wareSkuEntity);
                }
            }
        }
    }

}
